package com.yonyou.handler;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by WangXin on 2017/5/22.
 */
public class ExcelHandler {
    public List<List<String>> readXlsx(String path) throws IOException {

        //先获取获取整个Excel
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        List<List<String>> result = new ArrayList<List<String>>();
        //循环每一页，并处理当前循环页
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            //处理当前页，循环读取每一行
            for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);

                int minColIx = xssfRow.getFirstCellNum();
                int maxColIx = xssfRow.getLastCellNum();
                List<String> rowList = new ArrayList<String>();
                //遍历该行，获取每个cell元素并处理
                for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                    XSSFCell xssfCell = xssfRow.getCell(colIx);
                    if (xssfCell == null) {
                        rowList.add(null);
                        continue;
                    }
                    rowList.add(xssfCell.toString());
                }
                result.add(rowList);
            }
        }
        return result;
    }
}
